//
//  YCPlaceholderTextView.m
//  YCSchool
//
//  Created by gmall on 16/5/4.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "YCPlaceholderTextView.h"

@interface YCPlaceholderTextView()
@property (nonatomic, weak) UILabel *placeholderLabel;
@end

@implementation YCPlaceholderTextView


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        UILabel *placeholderLabel = [[UILabel alloc] init];
        placeholderLabel.numberOfLines = 0;
        [self addSubview:placeholderLabel];
        self.placeholderLabel = placeholderLabel;
        self.font = [UIFont systemFontOfSize:14];
        self.placeholderColor = [UIColor grayColor];
        self.contentOffset = CGPointMake(0, 5);
        self.textContainerInset = UIEdgeInsetsMake(5, 0, 0, 0);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

- (void)textDidChange:(NSNotification *)note
{
    self.placeholderLabel.hidden = self.hasText;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.placeholderLabel sizeToFit];
    CGRect frame = self.placeholderLabel.frame;
    frame.origin.x = 5;
    frame.origin.y = 5;
    frame.size.width = self.frame.size.width - 2 * frame.origin.x;
    self.placeholderLabel.frame = frame;
}

#pragma mark - setter
- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    
    self.placeholderLabel.text = placeholder;
    [self.placeholderLabel sizeToFit];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    
    self.placeholderLabel.textColor = placeholderColor;
}

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    
    self.placeholderLabel.font = font;
    [self.placeholderLabel sizeToFit];
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    
    self.placeholderLabel.hidden = self.hasText;
}

- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    self.placeholderLabel.hidden = self.hasText;
}



@end
